package com.extsci.webmail.web.service;

import com.extsci.webmail.common.entity.mail.Attachment;
import com.extsci.webmail.common.entity.mail.MailAttachment;
import com.extsci.webmail.common.util.MyFileUtils;
import com.extsci.webmail.exception.AttachmentException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.mail.internet.MimeUtility;
import java.io.*;
import java.util.List;

/**
 * 附件处理服务
 * @author ccoke
 */
@Service
public class AttachmentHandleService{
    @Value("${webmail.file.path}")
    public String filePath;

    @Value("${webmail.file.url}")
    public String fileUrl;


    /**
     * 将附件url转换为真实附件地址
     */
    public void parseMailAttachments(List<Attachment> attachments) throws AttachmentException {
        if (attachments == null || attachments.size() < 1) {
            return;
        }
        for (Attachment attachment: attachments) {
            String realPath = MyFileUtils.getFilePathByURL(attachment.getUri());
            String path = MyFileUtils.contactUri(filePath, realPath);
            if ("".equals(realPath) || !MyFileUtils.isExists(path)) {
                throw new AttachmentException(attachment.getUri());
            }
            attachment.setUri(path);
        }
    }

    /**
     * 删除邮件附件目录
     */
    public void deleteAttachmentFolder(String mailBoxType, List<Long> uids, String address){
        // filepath/resource/a@b.com/mailboxType/
        String relativePath = MyFileUtils.contactUri(filePath,
                MyFileUtils.FILE_SEPARATOR,
                MyFileUtils.RESOURCE,
                MyFileUtils.FILE_SEPARATOR,
                address,
                MyFileUtils.FILE_SEPARATOR,
                mailBoxType,
                MyFileUtils.FILE_SEPARATOR
        );
        uids.stream().forEach(uid -> {
            MyFileUtils.deleteDir(new File(relativePath + uid));
        });
    }

    public void save(List<MailAttachment> attachments, String filePath, String relativePath) throws IOException {
        for (MailAttachment attachment : attachments) {
            inputStream2Local(
                    attachment.getDataHandler().getInputStream(),
                    MyFileUtils.contactUri(filePath, relativePath, MyFileUtils.FILE_SEPARATOR, attachment.getCid()),
                    MimeUtility.decodeText(attachment.getDataHandler().getName())
            );
        }
    }

    /**
     * 将DataHandler存入本地,并返回文件信息
     */
    public Attachment inputStream2Local(InputStream inputStream, String filePath, String name) throws IOException {
        MyFileUtils.createDirs(filePath);
        String fileName = MyFileUtils.contactUri(filePath, MyFileUtils.FILE_SEPARATOR, name);
        // 判断文件是否存在
        if (!MyFileUtils.isExists(fileName)){
            // 将文件存入本地
            saveStream2File(inputStream, fileName);
        }
        return new Attachment().setName(name).setSize(MyFileUtils.getSize(fileName));
    }

    /*
     * 读取输入流中的数据保存至指定目录
     * */
    private void saveStream2File(InputStream is, String filePath) throws IOException {
        BufferedInputStream bis = new BufferedInputStream(is);
        File file = new File(filePath);
        BufferedOutputStream bos = new BufferedOutputStream(
                new FileOutputStream(file));
        int len;
        while ((len = bis.read()) != -1) {
            bos.write(len);
            bos.flush();
        }
        bos.close();
        bis.close();
    }

}
